package com.alianzamedica.controllers.tag;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.objectsearch.sqlsearch.ObjectSearch;
import org.w3c.dom.Document;

import com.alianzamedica.businessobject.Lot;
import com.alianzamedica.tools.Enviroment;
import com.alianzamedica.view.LotViewForm;

/**
 * @author Carlos
 * 
 */
public class LotSaveAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Enviroment env = Enviroment.getInstance();
		Document doc = env.getDocument();
		ObjectSearch search = new ObjectSearch(doc,
				"com.alianzamedica.connection.ConnectionImpl");
		LotViewForm lotView = (LotViewForm) form;
		Lot lot = lotView.getLot();
		Lot l = new Lot();
		l.setId(lotView.getId());
		String mensaje = "";
		if (!this.existsLot(l)) {
			search.insertObject(lot);
			mensaje = "Se ha insertado el lote correctamente";
		} else {
			search.updateObject(lot);
			mensaje = "Se ha actualizado el lote correctamente";
		}
		String linkRetorno = "/admin/tag/lotList.do";
		request.setAttribute("mensaje", mensaje);
		request.setAttribute("linkRetorno", linkRetorno);

		return mapping.findForward("success");
	}

	@SuppressWarnings("unchecked")
	private boolean existsLot(Lot l) throws Exception {
		Enviroment env = Enviroment.getInstance();
		Document doc = env.getDocument();
		ObjectSearch search = new ObjectSearch(doc,
				"com.alianzamedica.connection.ConnectionImpl");
		Iterator<Lot> iterator = search.searchObjects(l).iterator();
		if (iterator.hasNext()) {
			return true;
		} else {
			return false;
		}

	}

}
